import React, { useState, useEffect } from "react";
import {
  Card,
  Form,
  Input,
  InputNumber,
  Button,
  Row,
  Col,
  Table,
  Select,
  Space,
  Typography,
  Spin,
  Empty,
  Tabs,
  Tag,
  Alert,
  Statistic,
  Divider,
  theme,
} from "antd";
import {
  SearchOutlined,
  LineChartOutlined,
  TableOutlined,
  SwapOutlined,
  ReloadOutlined,
} from "@ant-design/icons";
import {
  LineChart,
  Line,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  Legend,
  ResponsiveContainer,
} from "recharts";
import { useTranslation } from "react-i18next";
import { useMessage } from "../contexts/MessageContext";
import { useWindowSize } from "../hooks/useWindowSize";
import { dataAPI } from "../services/api";
import dayjs from "dayjs";

const { Title, Text } = Typography;
const { Option } = Select;
const { TabPane } = Tabs;

const DataComparison = () => {
  const { t } = useTranslation();
  const message = useMessage();
  const { token } = theme.useToken();
  const { isMobile } = useWindowSize();
  const [form] = Form.useForm();

  // 状态管理
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState(null);
  const [activeTab, setActiveTab] = useState("chart");
  const [selectedLists, setSelectedLists] = useState(["list1", "list2"]);
  const [comparisonResult, setComparisonResult] = useState(null);

  // 监听选择的列表变化，自动重新比较
  useEffect(() => {
    if (data && selectedLists.length >= 2) {
      performComparison(data);
    }
  }, [selectedLists, data]);

  // 查询数据
  const fetchData = async (params) => {
    try {
      setLoading(true);
      const response = await dataAPI.queryGhyLast5(params);
      setData(response.data);

      // 自动进行比较
      if (response.data) {
        performComparison(response.data);
      }

      message.success("数据获取成功");
    } catch (error) {
      console.error("获取数据失败:", error);
      message.error("获取数据失败");
    } finally {
      setLoading(false);
    }
  };

  // 表单提交
  const handleSubmit = (values) => {
    fetchData(values);
  };

  // 数据比较功能
  const performComparison = (apiData) => {
    if (!apiData || selectedLists.length < 2) return;

    const [list1Name, list2Name] = selectedLists;
    const list1 = apiData[list1Name] || [];
    const list2 = apiData[list2Name] || [];

    console.log("比较数据:", {
      list1Name,
      list2Name,
      list1Length: list1.length,
      list2Length: list2.length,
    });

    // 按code分组
    const list1Codes = new Set(list1.map((item) => item.code));
    const list2Codes = new Set(list2.map((item) => item.code));

    console.log("Codes:", {
      list1Codes: Array.from(list1Codes),
      list2Codes: Array.from(list2Codes),
    });

    // 找出差异
    const list1Missing = Array.from(list2Codes).filter(
      (code) => !list1Codes.has(code)
    );
    const list2Missing = Array.from(list1Codes).filter(
      (code) => !list2Codes.has(code)
    );
    const common = Array.from(list1Codes).filter((code) =>
      list2Codes.has(code)
    );

    const result = {
      list1Name,
      list2Name,
      list1Missing,
      list2Missing,
      common,
      list1Count: list1.length,
      list2Count: list2.length,
    };

    console.log("比较结果:", result);
    setComparisonResult(result);
  };

  // 准备图表数据
  const getChartData = () => {
    if (!data) return [];

    const colors = ["#1890ff", "#52c41a", "#faad14", "#f5222d", "#722ed1"];

    // 获取每个列表第一项的时间作为名称
    const getListName = (listData, fallbackName) => {
      if (listData && listData.length > 0 && listData[0].updatedAt) {
        return dayjs.unix(listData[0].updatedAt).format("YYYY-MM-DD HH:mm");
      }
      return fallbackName;
    };

    return [
      {
        name: getListName(data.list1, "List1"),
        count: data.size1 || 0,
        data: data.list1 || [],
        color: colors[0],
        originalName: "list1",
      },
      {
        name: getListName(data.list2, "List2"),
        count: data.size2 || 0,
        data: data.list2 || [],
        color: colors[1],
        originalName: "list2",
      },
      {
        name: getListName(data.list3, "List3"),
        count: data.size3 || 0,
        data: data.list3 || [],
        color: colors[2],
        originalName: "list3",
      },
      {
        name: getListName(data.list4, "List4"),
        count: data.size4 || 0,
        data: data.list4 || [],
        color: colors[3],
        originalName: "list4",
      },
      {
        name: getListName(data.list5, "List5"),
        count: data.size5 || 0,
        data: data.list5 || [],
        color: colors[4],
        originalName: "list5",
      },
    ];
  };

  // 表格列定义
  const getTableColumns = () => [
    {
      title: "ID",
      dataIndex: "id",
      key: "id",
      width: 200,
      ellipsis: true,
    },
    {
      title: "样本",
      dataIndex: "sample",
      key: "sample",
      width: 80,
    },
    {
      title: "批次",
      dataIndex: "waybatch",
      key: "waybatch",
      width: 100,
    },
    {
      title: "设备编码",
      dataIndex: "waycode",
      key: "waycode",
      width: 100,
      render: (value) => <Tag color="blue">{value}</Tag>,
    },
    {
      title: "类型",
      dataIndex: "type",
      key: "type",
      width: 80,
    },
    {
      title: "批次号",
      dataIndex: "batch",
      key: "batch",
      width: 100,
    },
    {
      title: "编码",
      dataIndex: "code",
      key: "code",
      width: 80,
    },
    {
      title: "电压（V）",
      dataIndex: "voltage",
      key: "voltage",
      width: 80,
      render: (value) => `${(value / 100).toFixed(2)}`,
    },
    {
      title: "Mesa",
      dataIndex: "mesa",
      key: "mesa",
      width: 80,
    },
    {
      title: "角度",
      dataIndex: "angle",
      key: "angle",
      width: 80,
      render: (value) => `${value}°`,
    },
    {
      title: "温度（°C）",
      dataIndex: "tmp",
      key: "tmp",
      width: 80,
      render: (value) => `${(value / 100).toFixed(1)}`,
    },
    {
      title: "RSSI（dBm）",
      dataIndex: "rssi",
      key: "rssi",
      width: 80,
      render: (value) => `${value}`,
    },
    {
      title: "经度",
      dataIndex: "lng",
      key: "lng",
      width: 100,
      render: (value) => value?.toFixed(4),
    },
    {
      title: "纬度",
      dataIndex: "lat",
      key: "lat",
      width: 100,
      render: (value) => value?.toFixed(4),
    },
    {
      title: "更新时间",
      dataIndex: "updatedAt",
      key: "updatedAt",
      width: 160,
      render: (value) => dayjs.unix(value).format("YYYY-MM-DD HH:mm:ss"),
    },
  ];

  // 渲染统计卡片
  const renderStatistics = () => {
    if (!data) return null;

    // 获取时间名称的函数
    const getTimeTitle = (listData, fallbackName) => {
      if (listData && listData.length > 0 && listData[0].updatedAt) {
        return dayjs.unix(listData[0].updatedAt).format("YYYY-MM-DD HH:mm");
      }
      return fallbackName;
    };

    const stats = [
      {
        title: getTimeTitle(data.list1, "List1"),
        value: data.size1 || 0,
        color: "#1890ff",
      },
      {
        title: getTimeTitle(data.list2, "List2"),
        value: data.size2 || 0,
        color: "#52c41a",
      },
      {
        title: getTimeTitle(data.list3, "List3"),
        value: data.size3 || 0,
        color: "#faad14",
      },
      {
        title: getTimeTitle(data.list4, "List4"),
        value: data.size4 || 0,
        color: "#f5222d",
      },
      {
        title: getTimeTitle(data.list5, "List5"),
        value: data.size5 || 0,
        color: "#722ed1",
      },
    ];

    return (
      <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
        {stats.map((stat, index) => (
          <Col xs={12} sm={8} md={6} lg={4} xl={4} key={index}>
            <Card>
              <Statistic
                title={stat.title}
                value={stat.value}
                valueStyle={{ color: stat.color }}
                suffix="台"
              />
            </Card>
          </Col>
        ))}
        <Col xs={12} sm={8} md={6} lg={4} xl={4}>
          <Card>
            <Statistic
              title="总计"
              value={stats.reduce((sum, stat) => sum + stat.value, 0)}
              valueStyle={{ color: token.colorPrimary }}
              suffix="台"
            />
          </Card>
        </Col>
      </Row>
    );
  };

  // 渲染折线图
  const renderChart = () => {
    const chartData = getChartData();

    return (
      <Card
        title={
          <>
            <LineChartOutlined /> 数据量趋势图
          </>
        }
      >
        <ResponsiveContainer width="100%" height={450}>
          <LineChart
            data={chartData}
            margin={{ top: 20, right: 30, left: 20, bottom: 20 }}
          >
            <defs>
              <linearGradient id="colorUv" x1="0" y1="0" x2="0" y2="1">
                <stop
                  offset="5%"
                  stopColor={token.colorPrimary}
                  stopOpacity={0.8}
                />
                <stop
                  offset="95%"
                  stopColor={token.colorPrimary}
                  stopOpacity={0.1}
                />
              </linearGradient>
            </defs>
            <CartesianGrid
              strokeDasharray="3 3"
              stroke="#f0f0f0"
              opacity={0.6}
            />
            <XAxis
              dataKey="name"
              tick={{ fill: token.colorText, fontSize: 12 }}
              axisLine={{ stroke: token.colorBorder }}
              tickLine={{ stroke: token.colorBorder }}
            />
            <YAxis
              tick={{ fill: token.colorText, fontSize: 12 }}
              axisLine={{ stroke: token.colorBorder }}
              tickLine={{ stroke: token.colorBorder }}
            />
            <Tooltip
              contentStyle={{
                backgroundColor: token.colorBgContainer,
                border: `1px solid ${token.colorBorder}`,
                borderRadius: token.borderRadius,
                boxShadow: token.boxShadow,
              }}
              formatter={(value) => [`${value} 台`, "设备数量"]}
              labelStyle={{ color: token.colorText }}
            />
            <Legend />
            <Line
              type="monotone"
              dataKey="count"
              name="设备数量"
              stroke={token.colorPrimary}
              strokeWidth={4}
              strokeLinecap="round"
              strokeLinejoin="round"
              dot={{
                fill: "#fff",
                strokeWidth: 3,
                r: 6,
                stroke: token.colorPrimary,
              }}
              activeDot={{
                r: 8,
                stroke: token.colorPrimary,
                strokeWidth: 3,
                fill: "#fff",
                boxShadow: `0 0 10px ${token.colorPrimary}`,
              }}
              animationDuration={2000}
              animationBegin={0}
            />
          </LineChart>
        </ResponsiveContainer>
      </Card>
    );
  };

  // 渲染表格标签页
  const renderTableTabs = () => {
    if (!data) return <Empty description="暂无数据" />;

    const lists = ["list1", "list2", "list3", "list4", "list5"];

    // 获取时间名称的函数
    const getTimeTitle = (listData, listKey) => {
      if (listData && listData.length > 0 && listData[0].updatedAt) {
        return dayjs.unix(listData[0].updatedAt).format("YYYY-MM-DD HH:mm");
      }
      return listKey.toUpperCase();
    };

    return (
      <Card
        title={
          <>
            <TableOutlined /> 详细数据表
          </>
        }
      >
        <Tabs defaultActiveKey="list1">
          {lists.map((listKey) => {
            const listData = data[listKey] || [];
            const size = data[`size${listKey.replace("list", "")}`] || 0;
            const timeTitle = getTimeTitle(listData, listKey);

            return (
              <TabPane tab={`${timeTitle} (${size}台)`} key={listKey}>
                <Table
                  columns={getTableColumns()}
                  dataSource={listData}
                  rowKey="id"
                  scroll={{ x: 1500 }}
                  pagination={{
                    defaultPageSize: 10,
                    showSizeChanger: true,
                    showQuickJumper: true,
                    showTotal: (total) => `共 ${total} 台设备`,
                    pageSizeOptions: ["10", "20", "50", "100"],
                  }}
                />
              </TabPane>
            );
          })}
        </Tabs>
      </Card>
    );
  };

  // 渲染比较结果
  const renderComparison = () => {
    if (!comparisonResult) {
      return (
        <Card
          title={
            <>
              <SwapOutlined /> 数据对比分析
            </>
          }
        >
          <Empty description="请先查询数据" />
        </Card>
      );
    }

    const {
      list1Name,
      list2Name,
      list1Missing,
      list2Missing,
      common,
      list1Count,
      list2Count,
    } = comparisonResult;

    // 获取显示名称的函数
    const getDisplayName = (listName) => {
      const listData = data && data[listName];
      if (listData && listData.length > 0 && listData[0].updatedAt) {
        return dayjs.unix(listData[0].updatedAt).format("YYYY-MM-DD HH:mm");
      }
      return listName.toUpperCase();
    };

    return (
      <Card
        title={
          <>
            <SwapOutlined /> 数据对比分析
          </>
        }
      >
        <Space direction="vertical" style={{ width: "100%" }} size="large">
          <Alert
            message="比较说明"
            description="本功能将比较两个列表中设备的 Code 字段差异，找出缺失的设备编码"
            type="info"
            showIcon
            closable
          />
          {/* 比较配置 */}
          <Row gutter={16}>
            <Col span={12}>
              <Select
                placeholder="选择对比列表1"
                value={selectedLists[0]}
                onChange={(value) => {
                  if (value !== selectedLists[1]) {
                    setSelectedLists([value, selectedLists[1]]);
                  }
                }}
                style={{ width: "100%" }}
              >
                {["list1", "list2", "list3", "list4", "list5"].map((list) => {
                  const listData = data && data[list];
                  const timeTitle =
                    listData && listData.length > 0 && listData[0].updatedAt
                      ? dayjs
                          .unix(listData[0].updatedAt)
                          .format("YYYY-MM-DD HH:mm")
                      : list.toUpperCase();
                  return (
                    <Option
                      key={list}
                      value={list}
                      disabled={list === selectedLists[1]}
                    >
                      {timeTitle}{" "}
                      {data &&
                        `(${data[`size${list.replace("list", "")}`] || 0}台)`}
                    </Option>
                  );
                })}
              </Select>
            </Col>
            <Col span={12}>
              <Select
                placeholder="选择对比列表2"
                value={selectedLists[1]}
                onChange={(value) => {
                  if (value !== selectedLists[0]) {
                    setSelectedLists([selectedLists[0], value]);
                  }
                }}
                style={{ width: "100%" }}
              >
                {["list1", "list2", "list3", "list4", "list5"].map((list) => {
                  const listData = data && data[list];
                  const timeTitle =
                    listData && listData.length > 0 && listData[0].updatedAt
                      ? dayjs
                          .unix(listData[0].updatedAt)
                          .format("YYYY-MM-DD HH:mm")
                      : list.toUpperCase();
                  return (
                    <Option
                      key={list}
                      value={list}
                      disabled={list === selectedLists[0]}
                    >
                      {timeTitle}{" "}
                      {data &&
                        `(${data[`size${list.replace("list", "")}`] || 0}台)`}
                    </Option>
                  );
                })}
              </Select>
            </Col>
          </Row>

          {/* 统计信息 */}
          <Row gutter={16}>
            <Col xs={24} sm={6}>
              <Statistic
                title={`${getDisplayName(list1Name)}设备数`}
                value={list1Count}
                suffix="台"
              />
            </Col>
            <Col xs={24} sm={6}>
              <Statistic
                title={`${getDisplayName(list2Name)}设备数`}
                value={list2Count}
                suffix="台"
              />
            </Col>
            <Col xs={24} sm={4}>
              <Statistic
                title="共同设备"
                value={common.length}
                valueStyle={{ color: "#52c41a" }}
              />
            </Col>
            <Col xs={24} sm={4}>
              <Statistic
                title={`${getDisplayName(list1Name)}缺失`}
                value={list1Missing.length}
                valueStyle={{ color: "#f5222d" }}
              />
            </Col>
            <Col xs={24} sm={4}>
              <Statistic
                title={`${getDisplayName(list2Name)}缺失`}
                value={list2Missing.length}
                valueStyle={{ color: "#faad14" }}
              />
            </Col>
          </Row>

          <Divider />

          {/* 差异分析 */}
          {list1Missing.length > 0 && (
            <Alert
              message={`${list1Name.toUpperCase()} 缺失的设备Code`}
              description={
                <Space wrap>
                  {list1Missing.map((code) => (
                    <Tag color="red" key={code}>
                      {" "}
                      {code}
                    </Tag>
                  ))}
                </Space>
              }
              type="error"
              showIcon
            />
          )}

          {list2Missing.length > 0 && (
            <Alert
              message={`${list2Name.toUpperCase()} 缺失的设备Code`}
              description={
                <Space wrap>
                  {list2Missing.map((code) => (
                    <Tag color="orange" key={code}>
                      {" "}
                      {code}
                    </Tag>
                  ))}
                </Space>
              }
              type="warning"
              showIcon
            />
          )}

          {common.length > 0 && (
            <Alert
              message="共同设备Code"
              description={
                <Space wrap>
                  {common.map((code) => (
                    <Tag color="green" key={code}>
                      {" "}
                      {code}
                    </Tag>
                  ))}
                </Space>
              }
              type="success"
              showIcon
            />
          )}

          {list1Missing.length === 0 && list2Missing.length === 0 && (
            <Alert
              message="数据完全匹配"
              description="两个列表包含相同的设备Code，无差异"
              type="info"
              showIcon
            />
          )}
        </Space>
      </Card>
    );
  };

  return (
    <div style={{ padding: isMobile ? 12 : 24 }}>
      <Title level={2}>数据对比分析</Title>
      <div
        style={{
          color: "#8c8c8c",
          fontSize: "14px",
          marginTop: "8px",
          marginBottom: "16px",
        }}
      >
        此页面仅展示间隔1分钟以上的数据
      </div>
      {/* 查询表单 */}
      <Card title="查询条件" style={{ marginBottom: 24 }}>
        <Form
          form={form}
          layout={isMobile ? "vertical" : "inline"}
          onFinish={handleSubmit}
          initialValues={{
            code: "",
            batch: "",
          }}
        >
          <Form.Item
            name="code"
            label="网关编码"
            rules={[{ required: true, message: "请输入网关编码" }]}
          >
            <InputNumber placeholder="请输入网关编码" min={1} />
          </Form.Item>

          <Form.Item
            name="batch"
            label="批次"
            rules={[{ required: false, message: "请输入批次" }]}
          >
            <InputNumber placeholder="请输入批次" min={1} />
          </Form.Item>

          <Form.Item>
            <Space>
              <Button
                type="primary"
                htmlType="submit"
                icon={<SearchOutlined />}
                loading={loading}
              >
                查询数据
              </Button>
              <Button
                icon={<ReloadOutlined />}
                onClick={() => form.resetFields()}
              >
                重置
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>

      {/* 统计卡片 */}
      {renderStatistics()}

      {/* 主要内容区域 */}
      <Spin spinning={loading}>
        <Tabs activeKey={activeTab} onChange={setActiveTab}>
          <TabPane
            tab={
              <>
                <LineChartOutlined /> 数据趋势
              </>
            }
            key="chart"
          >
            {renderChart()}
          </TabPane>

          <TabPane
            tab={
              <>
                <SwapOutlined /> 数据对比
              </>
            }
            key="comparison"
          >
            {renderComparison()}
          </TabPane>

          <TabPane
            tab={
              <>
                <TableOutlined /> 详细数据
              </>
            }
            key="table"
          >
            {renderTableTabs()}
          </TabPane>
        </Tabs>
      </Spin>
    </div>
  );
};

export default DataComparison;
